package itypes

import (
	"server/game/model"
	"server/share/config"
	"server/share/define"

	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/logger"
	"github.com/hwcer/updater"
	"github.com/hwcer/updater/operator"
	"github.com/hwcer/yyds"
	"github.com/hwcer/yyds/players/player"
)

var Box = NewItemsIType(config.ITypeBox)
var Items = NewItemsIType(config.ITypeItems)
var Gacha = NewItemsIType(config.ITypeGacha)
var Order = NewItemsIType(config.ITypeOrder)

func init() {
	im := &model.Items{}
	its := []updater.IType{Box, Items, Ticket, Order, Gacha, ItemsGroup, ItemsPacks, ItemsBong}
	its = append(its, Egg, Chip)
	its = append(its, Unit, UnitBase)
	if err := updater.Register(updater.ParserTypeCollection, updater.RAMTypeAlways, im, its...); err != nil {
		logger.Panic(err)
	}
	//钻石消耗
	Items.SetListener(func(u *updater.Updater, op *operator.Operator) {
		if op.Type == operator.TypesSub && op.IID == define.ItemsZB {
			p := u.Player().(*player.Player)
			p.Emit(config.Data.Events.CostCoin, int32(op.Value))
		}
		if op.Type == operator.TypesAdd && op.IID == 60600007 && op.Value > 10 {
			p := u.Player().(*player.Player)
			logger.Alert("发现作弊，UID:%s,路径:%s,数量:%d", p.Uid(), p.Path, op.Value)
			if op.Value > 100 {
				op.Value = 0
			}
		}

	})
}

func NewItemsIType(id int32) *ItemsIType {
	i := &ItemsIType{}
	i.IType.id = id
	i.IType.creator = i.creator
	return i
}

type ItemsIType struct {
	IType
	attach  func(u *updater.Updater, item *model.Items) (any, error) //设置attach
	resolve func(u *updater.Updater, iid int32, val int64) error     //分解
}

func (this *ItemsIType) SetAttach(attach func(u *updater.Updater, item *model.Items) (any, error)) {
	this.attach = attach
}

func (this *ItemsIType) SetResolve(resolve func(u *updater.Updater, iid int32, val int64) error) {
	this.resolve = resolve
}

// Resolve 自动分解
func (this *ItemsIType) Resolve(u *updater.Updater, iid int32, val int64) error {
	if this.resolve != nil {
		return this.resolve(u, iid, val)
	}
	return nil
}

func (this *ItemsIType) Create(u *updater.Updater, iid int32, val int64) (*model.Items, error) {
	if i, err := this.creator(u, iid, val); err != nil {
		return nil, err
	} else {
		return i.(*model.Items), nil
	}
}

func (this *ItemsIType) creator(u *updater.Updater, iid int32, val int64) (any, error) {
	r := &model.Items{}
	r.Init(u, iid)
	r.OID = this.IType.ObjectId(u, iid)
	r.Bag = yyds.Config.GetIType(iid)
	r.Value = val
	r.Attach = values.Values{}
	if this.attach != nil {
		return this.attach(u, r)
	}
	return r, nil
}
